package com.demo.connectdbtest.module.tool.controller;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.demo.connectdbtest.module.tool.popoMapper.OmDeviceInfoMapper;
import com.demo.connectdbtest.module.tool.service.ToolService;
import com.demo.connectdbtest.module.tool.vo.DeviceInfoDTO;
import com.demo.connectdbtest.module.tool.vo.OmDeviceInfo;
import com.demo.connectdbtest.module.tool.vo.PromDataDTO;
import com.demo.connectdbtest.module.tool.vo.PromRespResult;
import com.demo.connectdbtest.module.tool.vo.ServiceStatusReqVO;
import com.demo.connectdbtest.module.tool.vo.StatisticDeviceDataDTO;
import com.demo.connectdbtest.module.util.JsonUtil;
import org.openqa.selenium.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/tool")
public class ToolController {

    private static final Logger log = LoggerFactory.getLogger(ToolController.class);

    @Autowired
    private ToolService toolService;

    @Autowired
    private OmDeviceInfoMapper omDeviceInfoMapper;

    /**
     * 统计不同设备的在线离线数
     *
     * @return
     */
    @PostMapping("/statistic/device/data")
    public List<Object> statisticDeviceData(@RequestBody StatisticDeviceDataDTO dto) {
        List<Object> respList = new ArrayList<>();
//        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getStatList())) {
//            return respList;
//        }

        //获取设备信息表的数据
        List<OmDeviceInfo> omDeviceInfos = omDeviceInfoMapper.selectAll();
        if (CollectionUtils.isEmpty(omDeviceInfos)) {
            return respList;
        }

        List<PromRespResult> handleList = new ArrayList<>();
        HashMap<String, List<PromRespResult>> handlerMap = new HashMap<>();
        List<String> statList = dto.getStatList();
        for (String item : statList) {
            //item = "{\"status\":\"success\",\"data\":{\"resultType\":\"matrix\",\"result\":[{\"metric\":{\"__name__\":\"up\",\"address\":\"10.252.176.74:9116\",\"devicename\":\"汇聚交换机\",\"instance\":\"10.52.116.1\",\"job\":\"snmp-exporter\",\"line_name\":\"十三号线\",\"station_code\":\"1310\",\"station_id\":\"293\",\"station_name\":\"官湖\",\"tenderSectionName\":\"E\"},\"values\":[[1721318400,\"0\"]]},{\"metric\":{\"__name__\":\"up\",\"address\":\"10.252.176.75:9116\",\"devicename\":\"汇聚交换机\",\"instance\":\"10.55.79.118\",\"job\":\"snmp-exporter\",\"line_name\":\"十三号线\",\"station_code\":\"1311\",\"station_id\":\"294\",\"station_name\":\"新沙\",\"tenderSectionName\":\"E\"},\"values\":[[1721318400,\"0\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.171.20:9100\",\"job\":\"node_exporter\",\"server\":\"开发平台服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.171.50:9100\",\"job\":\"node_exporter\",\"server\":\"存储服务ceph-01\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.113:9100\",\"job\":\"node_exporter\",\"server\":\"轨道交通-mysql8\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.15:9100\",\"job\":\"node_exporter\",\"server\":\"业务开发部-日志文件存储\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.17:19100\",\"job\":\"node_exporter\",\"server\":\"oracle-server k8s开发\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.18:19100\",\"job\":\"node_exporter\",\"server\":\"redis哨兵集群redis-sentinel-02\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.19:19100\",\"job\":\"node_exporter\",\"server\":\"redis哨兵集群redis-sentinel-03\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.22:9100\",\"job\":\"node_exporter\",\"server\":\"安检部使用-雷朋川2\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.24:9100\",\"job\":\"node_exporter\",\"server\":\"安检部使用-雷朋川1\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.2:9100\",\"job\":\"node_exporter\",\"server\":\"电子发票测试环境\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.30:9100\",\"job\":\"node_exporter\",\"server\":\"南大数据库-gbase\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.42:19100\",\"job\":\"node_exporter\",\"server\":\"测试部-测试环境\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.45:19100\",\"job\":\"node_exporter\",\"server\":\"nacos\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.46:9100\",\"job\":\"node_exporter\",\"server\":\"安检服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.50:19100\",\"job\":\"node_exporter\",\"server\":\"redis哨兵集群redis-sentinel-01\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.53:9100\",\"job\":\"node_exporter\",\"server\":\"智慧收益项目-帆软01\"},\"values\":[[1721318400,\"0\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.72:9100\",\"job\":\"node_exporter\",\"server\":\"智慧安检应用服务器-2\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.73:9100\",\"job\":\"node_exporter\",\"server\":\"智慧安检应用服务器-3\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.176.75:9100\",\"job\":\"node_exporter\",\"server\":\"智慧安检存储服务器-1\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.21.12:9100\",\"job\":\"node_exporter\",\"server\":\"大数据测试机-3(外部联调环境)\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.39.11:9100\",\"job\":\"node_exporter\",\"server\":\"elk日志与监控服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.39.18:9100\",\"job\":\"node_exporter\",\"server\":\"智慧安检集中判图项目\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.252.39.23:9100\",\"job\":\"node_exporter\",\"server\":\"安检部人脸项目使用-20210318\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.10:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.11:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.12:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.13:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.14:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.15:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.16:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.17:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.18:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"0\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.19:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"0\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.2:19100\",\"job\":\"node_exporter\",\"line_name\":\"十八号线\",\"server\":\"sims-jg01,sims-rf01,sims-sim01\",\"station_code\":\"9918\",\"station_id\":\"9918\",\"station_name\":\"横沥\",\"tenderSectionName\":\"E\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.3:19100\",\"job\":\"node_exporter\",\"line_name\":\"十三号线\",\"server\":\"sims-jg02,sims-im03\",\"station_code\":\"1308\",\"station_id\":\"291\",\"station_name\":\"白江\",\"tenderSectionName\":\"E\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.6:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.7:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.8:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]},{\"metric\":{\"__name__\":\"up\",\"instance\":\"10.53.5.9:19100\",\"job\":\"node_exporter\",\"server\":\"新运通云服务器\"},\"values\":[[1721318400,\"1\"]]}]}}";
//            String path = JsonUtil.class.getClassLoader().getResource("stat_device_num_by_type.json").getPath();
//            String path = JsonUtil.class.getClassLoader().getResource("device-monitor-2024-08-08-03-17-00.json").getPath();
//            String path = JsonUtil.class.getClassLoader().getResource("device-monitor-2024-08-08-02-18-00.json").getPath();
//            String path = JsonUtil.class.getClassLoader().getResource("device-monitor-2024-08-08-05-08-00.json").getPath();
            String path = JsonUtil.class.getClassLoader().getResource("deivice-monitor-2024-08-08-05-11-00.json").getPath();
//            String path = JsonUtil.class.getClassLoader().getResource("test111-device-monitor-2024-08-08-02-18-00.json").getPath();
            item = JsonUtil.readJsonFile(path);

            PromDataDTO parseData = JSONObject.parseObject(item, PromDataDTO.class);
            System.out.println("解析后的json数据");
//            System.out.println(JSONObject.toJSONString(parseData));
//            System.out.println(parseData);

            //匹配ip的数据才统计处理
            if (Objects.nonNull(parseData.getData()) && !CollectionUtils.isEmpty(parseData.getData().getResult())) {
                List<PromRespResult> result = parseData.getData().getResult();
                for (PromRespResult promRespResult : result) {
                    if (Objects.nonNull(promRespResult.getMetric()) && !StringUtils.isEmpty(promRespResult.getMetric().getInstance())) {
                        String instance = promRespResult.getMetric().getInstance();
                        if (StringUtils.isEmpty(instance)) {
                            continue;
                        }
                        boolean contains = instance.contains(":");
                        if (contains) {
                            System.out.println(promRespResult.getMetric().getInstance());
                            instance = promRespResult.getMetric().getInstance().split(":")[0];
                        }
                        String finalInstance = instance;
                        List<OmDeviceInfo> collect = omDeviceInfos.stream().filter(item1 ->
                                item1.getDeviceIp().equals(finalInstance)
                        ).collect(Collectors.toList());

                        if (collect.size() > 0) {
                            String deviceType = collect.get(0).getDeviceType();
                            if (deviceType.equals("CPU") || "GPU".equals(deviceType)) {
                                System.out.println("cpu或者gup的服务器");
                                System.out.println(promRespResult);
                            }
                            promRespResult.setDeviceType(deviceType);
                            handleList.add(promRespResult);
                            if (handlerMap.containsKey(deviceType)) {
                                List<PromRespResult> promRespResults = handlerMap.get(deviceType);
                                promRespResults.add(promRespResult);
                                handlerMap.put(deviceType, promRespResults);
                            } else {
                                List<PromRespResult> promRespResults = new ArrayList<>();
                                promRespResults.add(promRespResult);
                                handlerMap.put(deviceType, promRespResults);
                            }
                        }
                    }
                }
            }
        }

        if (CollectionUtils.isEmpty(handleList)) {
            //return "没有要处理的数据";
            System.out.println("没有要处理的数据");
            return null;
        }
        System.out.println("数量总数：" + handleList.size());

        //


        //根据设备类型去统计 key：设备类型 value:处理统计的数据
        for (Map.Entry<String, List<PromRespResult>> entryData : handlerMap.entrySet()) {
            Integer totalDeviceNum = handleList.size();
            Integer onlineDeviceNum = 0;
            Integer offlineDeviceNum = 0;
            List<PromRespResult> value = entryData.getValue();
            //value : 需要处理的数据
            for (PromRespResult promRespResult : value) {
                if (!CollectionUtils.isEmpty(promRespResult.getValues())) {
                    Object status = promRespResult.getValues().get(0).get(1);
                    if (Objects.nonNull(status)) {
                        String strStatus = (String) status;
                        if ("1".equals(status)) {
                            onlineDeviceNum = onlineDeviceNum + 1;
                        } else {
                            offlineDeviceNum = offlineDeviceNum + 1;
                        }
                    }
                }
            }

            // 统计结果
            JSONObject jsonObject = new JSONObject();
            BigDecimal onlineRate = new BigDecimal(0);
            BigDecimal offlineRate = new BigDecimal(0);
            if (totalDeviceNum != 0) {
                onlineRate = BigDecimal.valueOf(onlineDeviceNum).divide(BigDecimal.valueOf(totalDeviceNum), 3, RoundingMode.HALF_UP);
                offlineRate = BigDecimal.valueOf(offlineDeviceNum).divide(BigDecimal.valueOf(totalDeviceNum), 3, RoundingMode.HALF_UP);
            }

            System.out.println(onlineRate.toString());
            jsonObject.put(entryData.getKey(), "总数:" + totalDeviceNum + ",在线数：" + onlineDeviceNum + ",离线数：" +
                    offlineDeviceNum + ",在线率：" + onlineRate + ",离线率：" + offlineRate);

            jsonObject.put(entryData.getKey(), "在线数：" + onlineDeviceNum + ",离线数：" +
                    offlineDeviceNum);
            respList.add(jsonObject);
        }

        return respList;
    }


    //设备在线监控
    @PostMapping("/statistic/device/status/minotor")
    public List<Object> statisticDeviceStatusMonitor(@RequestBody StatisticDeviceDataDTO dto) {
        return toolService.statisticDeviceStatusMonitor(dto);
    }


    //服务器在线监控
    @PostMapping("/statistic/server/device/minotor")
    public List<Object> monitorServerDevice(@RequestBody StatisticDeviceDataDTO dto) {
        return toolService.monitorServerDevice(dto);
    }

    //服务在线监控
    @PostMapping("/statistic/service/device/minotor")
    public List<Object> monitorServiceDevice(@RequestBody StatisticDeviceDataDTO dto) {
        //return toolService.monitorServiceDevice(dto);
        return toolService.monitorServiceDeviceNotMatch(dto);
    }


    //测试服务服务是否正常
    @GetMapping("/service/mock/status/get")
    public JSONObject testServiceStatusGet(@RequestParam Boolean boy, Integer userId, String username) {
        System.out.println("testServiceStatusGet接收的参数userId=" + userId);
        System.out.println("testServiceStatusGet接收的参数username=" + username);
        System.out.println("testServiceStatusGet接收的参数boy=" + boy);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "8000");
        jsonObject.put("message", "成功");
        JSONObject data = new JSONObject();
        data.put("ncode", "8000");
        jsonObject.put("data", data);
        return jsonObject;
    }

    //测试服务服务是否正常
    @PostMapping("/service/mock/status/post")
    public JSONObject testServiceStatusPost(@RequestBody ServiceStatusReqVO vo) {
        System.out.println("testServiceStatusPost=" + JSONObject.toJSONString(vo));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "8000");
        jsonObject.put("message", "成功");
        JSONObject data = new JSONObject();
        data.put("ncode", "8000");
        jsonObject.put("data", data);
        return jsonObject;
    }

    //统计光电口启用状态   光电口启用状态 ifAdminStatus
    @GetMapping("/statistic/light/entrance/enable")
    public JSONObject statisticLightEntranceEnableStatus(@RequestParam(required = false) String deviceIp) {
        return toolService.statisticLightEntranceEnableStatus(deviceIp);
    }

    //统计光电口在线离线状态  ifOperStatus
    @GetMapping("/statistic/light/entrance/online")
    public JSONObject statisticLightEntranceOnlineStatus(@RequestParam(required = false) String deviceIp) {
        return toolService.statisticLightEntranceOnlineStatus(deviceIp);
    }

    //统计node-exporter的数据
    @GetMapping("/statistic/node/exporter/target")
    public JSONObject statisticNodeExporterTarget(@RequestParam(required = false) String stationId, @RequestParam(required = false) String stationCode) {
        return toolService.statisticNodeExporterTarget(stationId, stationCode);
    }

}
